package com.duan.nowcoder.community.service;

import com.duan.nowcoder.community.entity.DiscussPost;
import com.duan.nowcoder.community.mapper.DiscussPostMapper;
import com.duan.nowcoder.community.util.CommunityConstant;
import com.duan.nowcoder.community.util.SensitiveWordsFilter;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostServiceImpl implements DiscussPostService, CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(DiscussPostServiceImpl.class);
    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveWordsFilter sensitiveWordsFilter;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;
    //caffeine核心接口：cache,loadingCache,AsyncLoadingCache;
    //帖子列表缓存
    private LoadingCache<String, List<DiscussPost>> postListCache;
    //帖子总数缓存
    private LoadingCache<Integer, Integer> postRowsCache;

    @PostConstruct
    public void init() {
        //初始化帖子列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Override
                    public @Nullable List<DiscussPost> load(String key) throws Exception {
                        if (key == null || key.length() == 0) {
                            throw new IllegalArgumentException("参数错误");
                        }
                        String[] params = key.split(":");
                        if (params == null || params.length != 2) {
                            throw new IllegalArgumentException("参数错误");
                        }
                        int offset = Integer.parseInt(params[0]);
                        int limit = Integer.parseInt(params[1]);
                        //此处可以添加二级缓存：redis->mysql
                        logger.debug("load post list from DB");
                        return discussPostMapper.selectDiscussPost(0, offset, limit, 1);
                    }
                });
        //初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(Integer key) throws Exception {
                        logger.debug("load post rows from DB");
                        return discussPostMapper.selectDiscussPostRows(key);
                    }
                });
    }

    @Override
    public List<DiscussPost> selectDiscussPost(int userId, int offset, int limit, int sortMode) {
        if (userId == 0 && sortMode == 1) {
            return postListCache.get(offset + ":" + limit);

        }
        logger.debug("load post list from DB");
        return discussPostMapper.selectDiscussPost(userId, offset, limit, sortMode);
    }

    @Override
    public int selectDiscussPostRows(int userId) {
        if (userId == 0) {
            return postRowsCache.get(userId);
        }
        logger.debug("load post rows from DB");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    @Override
    public int addDiscussPost(DiscussPost discussPost) {
        if (discussPost == null) throw new IllegalArgumentException("参数内容不得为空");

        //对特殊字符进行转义
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent((HtmlUtils.htmlEscape(discussPost.getContent())));
        //对敏感词进行过滤
        discussPost.setTitle(sensitiveWordsFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveWordsFilter.filter(discussPost.getContent()));

        return discussPostMapper.insertDiscussPost(discussPost);
    }

    @Override
    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    @Override
    public int updatePostCommentCount(int postId, int count) {
        return discussPostMapper.updatePostCommentCount(postId, count);
    }

    @Override
    public int updatePostStatus(int postId, int status) {
        return discussPostMapper.updatePostStatus(postId, status);
    }

    @Override
    public int updatePostType(int postId, int type) {
        return discussPostMapper.updatePostType(postId, type);
    }

    @Override
    public int updateSCore(int postId, double score) {
        return discussPostMapper.updateScore(postId, score);
    }
}
